import copy
import json
import threading
import time
from datetime import datetime
from kafka import KafkaProducer


"""
生成geojson文件
"""
def geojson():
    result = {"type": "FeatureCollection", "features": []}
    one_point = {"type": "Feature", "properties": {}, "geometry": {"coordinates": [], "type": "Point"}}
    with open(r"D:\GJ\project\SiChuan\NaQian\device_info-0714.json", "r", encoding="utf-8") as f:
        data = json.load(f)
        up_data = data["device_info"]["up"]
        down_data = data["device_info"]["down"]
        kakou_data = data["device_info"]["kakou"]
        for key, data2 in down_data.items():
            one = copy.deepcopy(one_point)
            one["geometry"]["coordinates"] = [data2["longitude"], data2["latitude"]]
            result["features"].append(one)
    with open("down_device_geojson-0714.json", "w", encoding="utf-8") as f:
        json.dump(result, f, ensure_ascii=False, indent=4)


def get_dist(staion):
    dist_list = staion.split("+")
    km = dist_list[0][-4:]
    m = dist_list[1][:3]
    return int(km) * 1000 + int(m)


def get_config():
    device_info_path = "./Config/device_info.json"
    with open(device_info_path, "r", encoding="utf-8") as f:
        data = json.load(f)
    up_list = data["list_info"]["up"]
    down_list = data["list_info"]["down"]
    kakou_list = data["list_info"]["kakou"]
    # up_data = data["device_info"]["up"]
    # down_data = data["device_info"]["down"]
    # kakou_data = data["device_info"]["kakou"]
    up_dict = {}
    up_num = 1000
    for i in range(len(up_list) - 1):
        up_num += 1
        up_dis = get_dist(up_list[i])
        down_dis = get_dist(up_list[i+1])
        dist = (down_dis - up_dis) / 1000
        up_dict[str(up_num)] = {
            "up_gantry_id": [up_list[i]],
            "down_gantry_id": [up_list[i+1]],
            "time_interval": 5,
            "time_move": 0.5,
            "dist": dist,
            "car_pass_time": dist,
            "car_max_speed": 80,
            "car_min_speed": 60,
            "is_fork": 0
        }
    down_dict = {}
    down_num = 2000
    for i in range(len(down_list) - 1):
        down_num += 1
        up_dis = get_dist(down_list[i])
        down_dis = get_dist(down_list[i+1])
        dist = (down_dis - up_dis) / 1000
        down_dict[str(down_num)] = {
            "up_gantry_id": [down_list[i]],
            "down_gantry_id": [down_list[i+1]],
            "time_interval": 5,
            "time_move": 0.5,
            "dist": dist,
            "car_pass_time": dist,
            "car_max_speed": 80,
            "car_min_speed": 60,
            "is_fork": 0
        }
    kakou_dict = {}
    kakou_num = 2000
    for i in range(len(kakou_list) - 1):
        kakou_num += 1
        up_dis = get_dist(kakou_list[i])
        down_dis = get_dist(kakou_list[i + 1])
        dist = (down_dis - up_dis) / 1000
        kakou_dict[str(kakou_num)] = {
            "up_gantry_id": [kakou_list[i]],
            "down_gantry_id": [kakou_list[i + 1]],
            "time_interval": 5,
            "time_move": 0.5,
            "dist": dist,
            "car_pass_time": dist,
            "car_max_speed": 80,
            "car_min_speed": 60,
            "is_fork": 0
        }
    all_data = {
        "up": up_dict,
        "down": down_dict
    }
    try:
        file_path = r"D:\GJ\project\SiChuan\NaQian\sichuan-naqian-project\Config\conmnn.json"
        with open(file_path, "w", encoding="utf-8") as ff:
            json.dump(all_data, ff, ensure_ascii=False, indent=4)
        print("生成配置文件成功")
    except Exception as e:
        print("写入文件失败:", str(e))

# get_config()


def kafka_send(topic):
    producer = KafkaProducer(bootstrap_servers="10.102.1.113:9092",
                             value_serializer=lambda x: json.dumps(x).encode('utf-8'))
    # topic = "e1_data_nq01"
    log_path = r"D:\下载\飞书文件下载\2025-06-25-14-12-51\kako_data.log"
    init_time = None
    diff = 0
    with open(log_path, 'r', encoding='utf-8') as f:
        for line in f:
            msg = json.loads(line.strip())
            if init_time is None:
                init_time = msg["globalTime"]
                diff = int(time.time() * 1000) - init_time
                print("初始时间:", init_time, "时间差:", diff)
            else:
                dealy = (msg["globalTime"] - (int(time.time() * 1000) - diff)) / 1000
                print("时间差:", dealy, "当前时间:", time.time(), "初始时间:", msg["globalTime"]/1000, (int(time.time() * 1000) - diff)/1000)
                if dealy > 0:
                    time.sleep(dealy)
                # init_time = msg["globalTime"]
            # print("发送数据", msg)
            producer.send(topic, value=msg)
            print("发送数据111", time.time(), time.time()-init_time/1000)

#
# threading.Thread(target=kafka_send, args=("e1_data_nq01", )).start()
# threading.Thread(target=kafka_send, args=("e1_data_na02", )).start()


def get_result():
    result = {"timestamp": 1750821776, "devices": [
        {"deviceId": "A", "heartbeat": 1, "clock": 0, "delay": 0, "precision": 100, "total": 809, "positive": 0,
         "missed": 0, "incorrect": 0},
        {"deviceId": "B", "heartbeat": 1, "clock": 0, "delay": 0, "precision": 88.37, "total": 817, "positive": 722,
         "missed": 0, "incorrect": 95},
        {"deviceId": "C", "heartbeat": 1, "clock": 0, "delay": 0, "precision": 89.47, "total": 817, "positive": 731,
         "missed": 0, "incorrect": 86},
        {"deviceId": "D", "heartbeat": 1, "clock": 0, "delay": 0, "precision": 91.2, "total": 807, "positive": 736,
         "missed": 10, "incorrect": 71},
        {"deviceId": "E", "heartbeat": 1, "clock": 0, "delay": 0, "precision": 88.49, "total": 808, "positive": 715,
         "missed": 0, "incorrect": 93},
        {"deviceId": "F", "heartbeat": 1, "clock": 0, "delay": 0, "precision": 87.23, "total": 799, "positive": 697,
         "missed": 9, "incorrect": 102},
        {"deviceId": "G", "heartbeat": 1, "clock": 0, "delay": 0, "precision": 88.06, "total": 804, "positive": 708,
         "missed": 0, "incorrect": 96},
        {"deviceId": "H", "heartbeat": 1, "clock": 0, "delay": 0, "precision": 90.15, "total": 802, "positive": 723,
         "missed": 2, "incorrect": 79},
        {"deviceId": "I", "heartbeat": 1, "clock": 0, "delay": 0, "precision": 89.81, "total": 805, "positive": 723,
         "missed": 0, "incorrect": 82},
        {"deviceId": "J", "heartbeat": 1, "clock": 0, "delay": 0, "precision": 87.77, "total": 801, "positive": 703,
         "missed": 4, "incorrect": 98},
        {"deviceId": "K", "heartbeat": 1, "clock": 0, "delay": 0, "precision": 87.78, "total": 270, "positive": 237,
         "missed": 531, "incorrect": 33}]}
    for i in result["devices"]:
        print(i["deviceId"], i["positive"], i["incorrect"], i["missed"], i["precision"])


# get_result()


def build_pairs(seq, skip_dict, skip_value=1):
    """
    构建两两组合，跳过 skip_dict 中标记为 skip_value 的元素，
    并将这些元素前后的两个有效元素合并成一个组合。
    """
    result = []
    i = 0
    while i < len(seq):
        current = seq[i]

        # 如果当前元素是跳过项，直接跳到下一个
        if skip_dict.get(current, 0) == skip_value:
            i += 1
            continue

        # 寻找下一个非跳过项
        next_index = i + 1
        while next_index < len(seq) and skip_dict.get(seq[next_index], 0) == skip_value:
            next_index += 1

        # 如果找到了有效的下一项，组成对
        if next_index < len(seq):
            result.append([current, seq[next_index]])
            i = next_index  # 更新当前位置
        else:
            break  # 没有更多可配对的项了

    return result


def csv_save():
    import csv

    # 要写入的数据（字典列表）
    # data = [
    #     {"Name": "Alice", "Age": 30, "City": "New York"},
    #     {"Name": "Bob", "Age": 25, "City": "Los Angeles"},
    #     {"Name": "Charlie", "Age": 35, "City": "Chicago"}
    # ]

    beizhu = "注：经纬度是指相机抓拍断面的经纬度，小数点后8位，距离单位为千米，是距离上游的长度，如果为首个断面，填0，保留小数点后3位，方向为“上行”或“下行”，分合流为“有”或“无”，基站号需全局唯一"
    # 定义字段名
    fieldnames = ["IP", "经度", "纬度", "桩号", "方向", "分合流", "基站号", beizhu]

    # 打开文件并写入数据
    with open('config.csv', mode='w', newline='', encoding='utf-8') as file:
        writer = csv.DictWriter(file, fieldnames=fieldnames)

        writer.writeheader()  # 写入表头
        # writer.writerows(data)  # 写入数据行

    print("CSV文件已生成（字典格式）。")

# csv_save()

# a = [
#     (105.53438359, 27.78260382),
#     (105.53461439, 27.78320409),
#     (105.56285967, 27.80023948),
#     (105.56280305, 27.80040225),
#     (105.56402878, 28.01149755),
#     (105.56358011, 28.01113832),
#     (105.56301139, 28.04760149),
#     (105.56271092, 28.04767015),
#     (105.32103014, 28.44781314),
#     (105.32051117, 28.44783874),
#     (105.31973693, 28.46492636),
#     (105.31932822, 28.46488249),
#     (105.33547695, 28.62837124),
#     (105.33521675, 28.62866145),
#     (105.34576983, 28.64014172),
#     (105.3452033, 28.64009006),
#     (105.33650871, 28.67964851),
#     (105.33631236, 28.67937209),
#     (105.33593479, 28.69704269),
#     (105.33568447, 28.69735477),
# ]

# producer = KafkaProducer(bootstrap_servers="172.20.8.74:59092", value_serializer=lambda x: json.dumps(x).encode('utf-8'))
# while True:
#
#     # msg = {
#     #     "eventCode": "20250710174057",
#     #     "alertCategory": 101,
#     #     "eventStake": "DN_K700+400",
#     #     "beginTime": 1752140614123,
#     #     "laneIds": "1,2,3,4,99",
#     #     "level": 3,
#     #     "deviceStakes": "K700+400",
#     #     "deviceId": "57",
#     #     "refreshTime": 1752140624123,
#     #     "eventSection": 3
#     # }
#     # topic = "b5_data_wanji"
#     # producer.send(topic, value=msg)
#     # print("发送数据", time.time())
#     # topic = "e1_data_nq01"
#     log_path = r"C:\Users\wanji\Desktop\20250708-000000_20250710-180000.json"
#     with open(log_path, 'r', encoding='utf-8') as f:
#         for line in f:
#             msg = json.loads(line.strip())
#             topic = "b5_data_wanji"
#             msg["beginTime"] = int(time.time() * 1000)
#             msg["refreshTime"] = int(time.time() * 1000)
#             producer.send(topic, value=msg)
#             print("发送数据", time.time())
#             time.sleep(30)

import pandas as pd

csv_path = "device_info.xlsx"

# # 读取CSV文件
df = pd.read_excel(csv_path, engine='openpyxl')

# 显示前几行数据，默认显示前5行
print(df.head())
